/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb.common;

import entity.Account;
import entity.Persona;
import facade.AccountFacade;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.security.auth.login.AccountException;

/**
 *
 * @author Carmela
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class AccountManager implements AccountManagerLocal {

    @EJB
    private TripleDESLocal tripleDES;
    @PersistenceContext(unitName = "E-Market-ejbPU")
    private EntityManager em;
    @EJB
    private AccountFacade accountFacade;

    @Override
    public boolean isRegistrato(Account a) {
        Query q = em.createNamedQuery("Account.isRegistrato");
        q.setParameter(1, a.getEmail());
        List<Account> l = q.getResultList();
        if (!l.isEmpty()) {
            return true;
        }
        return false;
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @Override
    public void creaAccount(Account a) {
        accountFacade.create(a);
    }

    @Override
    public Account ottieniAccount(Account a) {

        Query q = em.createNamedQuery("Account.isRegistrato");
        q.setParameter(1, a.getEmail());
        return (Account) q.getSingleResult();
    }// ottieniAccount

    @Override
    public void modificaPassword(String newPassword, Long idAccount) throws AccountException {
        if (esiste(idAccount)) {
            Account a = accountFacade.find(idAccount);
            try {
                a.setPassword(tripleDES.encrypt(newPassword));
            } catch (Exception ex) {
                Logger.getLogger(AccountManager.class.getName()).log(Level.SEVERE, null, ex);
                return;
            }
            accountFacade.edit(a);
        } else {
            throw new AccountException();
        }
    }

    @Override
    public boolean esiste(Long idAccount) {
        Query q = em.createNamedQuery("account.exist");
        q.setParameter(1, idAccount);
        if (!q.getResultList().isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    public Persona cercaPersona(String email) {
        if (email == null) {

            throw new NullPointerException();
        }

        Query q = em.createNamedQuery("account.ottieniPersona");
        q.setParameter(1, email);

        return (Persona) q.getSingleResult();
    }
}
